const { createController, makeInvoker } = require('awilix-express')
const { Router } = require('express')
const { responseHelper } = require('../helper')

const api = makeInvoker(
  ({ register, getUserInfo, login, getAuthMenu, modifyPassword }) => {
    return {
      login: responseHelper(async (req, res) => {
        const token = await login.execute({
          ip: req.ip,
          ...req.body,
        })
        return token.accessToken
      }),
      register: responseHelper(async (req, res) => {
        return await register.execute(req.body)
      }),
      getUserInfo: responseHelper(async (req, res) => {
        const tokenStr = req.headers['authorization'].replace(`Bearer `, '')
        return await getUserInfo.execute(tokenStr)
      }),
      getAuthMenu: responseHelper(async (req, res) => {
        return await getAuthMenu.execute(req.query, req.user)
      }),
      modifyPassword: responseHelper(async (req, res) => {
        return await modifyPassword.execute(req.body, req.user)
      }),
    }
  }
)

module.exports = ({ all, auth }) => {
  const router = Router()
  router
    .post('/login', api('login'))
    .post('/register', api('register'))
    .get('/info', all, api('getUserInfo'))
    .get('/menu', all, api('getAuthMenu'))
    .post('/modifyPassword', all, api('modifyPassword'))

  return router
}
